/**
 * @Author:Geln Yang
 * @Created:2008-7-30 $ Revision: 1.0 $ $ Author: Geln Yang $ $ Date: 2008-7-30 $
 */
package com.hgy.commonsale.core.webwork.intercepter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.geln.web.Constants;
import org.geln.web.context.ISessionContext;
import com.hgy.commonsale.service.IUserManager;
import com.hgy.commonsale.user.domain.User;
import com.hgy.commonsale.webui.action.ProtectedAction;
import com.hgy.commonsale.webui.action.user.LoginAction;
import com.hgy.commonsale.webui.context.IApplicationSessionContext;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.Interceptor;

/**
 * @Author:Geln Yang
 * @Created:2008-7-30
 */
public class LoginInterceptor implements Interceptor {
	private IUserManager userManager;

	private IApplicationSessionContext sessionContext;

	public void destroy() {
	}

	public void init() {
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		Action action = (Action) invocation.getAction();

		if (action instanceof ProtectedAction) {
			ProtectedAction protectedAction = (ProtectedAction) action;
			User user = protectedAction.getCurrentUser();
			if (user != null) {
				return invocation.invoke();
			}
			HttpServletRequest request = ServletActionContext.getRequest();
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				String account = "", password = "";
				for (int i = 0; i < cookies.length; i++) {
					if (cookies[i].getName().equalsIgnoreCase(Constants.COOKIE_NAME)) {
						account = cookies[i].getValue();
					}
					if (cookies[i].getName().equalsIgnoreCase(Constants.COOKIE_PASSWORD)) {
						password = cookies[i].getValue();
					}
					if (!account.equals("") && !password.equals("")) {
						break;
					}
				}

				if (!account.equals("") && password.length() == User.PASSWORD_ENCODE_LENGTH) {
					user = userManager.getUserByAccount(account);
					if (user.authorize(password)) {
						protectedAction.setCurrentUser(user);
						return invocation.invoke();
					}
				}
			}
			try {
				String originalURL = (String) sessionContext.getResource(ISessionContext.ORIGINAL_URL);
				if (originalURL == null || action.getClass().equals(LoginAction.class)) {
					sessionContext.unbindResource(ISessionContext.ORIGINAL_URL);
				}
			} catch (Exception E) {
			}
			return Action.LOGIN;
		}
		return invocation.invoke();

	}

	public void setUserManager(IUserManager userManager) {
		this.userManager = userManager;
	}

	public void setSessionContext(IApplicationSessionContext sessionContext) {
		this.sessionContext = sessionContext;
	}
}
